<?php
/**
 * QuantityUserRepo.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-08-09 11:31:01
 * @modified    2023-08-09 11:31:01
 *
 */

namespace App\Repositories;

use App\Models\DeptModel;
use App\Models\UserModel;
use App\Services\DeptService;
use App\Services\ImageServ;

class QuantityUserRepo
{
    const DEPT_NAME = '品质部';

    // 品质工程师列表
    public static function getList()
    {
        // 工程师名称
        $name = trim(request('name', ''));
        // 区域ID
        $deptId = intval(request('dept_id', ''));

        $engineers = SettingRepo::getDataByKey(SettingRepo::KEY_PB_ENGINEER);
        if (empty($engineers)) {
            return [];
        }
        $results = [];
        foreach ($engineers as $engineer) {
            $itemDeptId = $engineer['dept_id'];
            $itemUserName = $engineer['user_name'];
            if ($deptId && $itemDeptId != $deptId) {
                continue;
            }
            if ($name && strrpos($itemUserName, $name) === false) {
                continue;
            }
            $user = UserModel::find($engineer['user_id']);
            $results[$engineer['dept_name']][] = [
                'dept_name' => $engineer['dept_name'],
                'user_name' => $engineer['user_name'],
                'user_id' => $engineer['user_id'],
                'avatar_url' => (new ImageServ($user->avatar ?? ''))->getUrl(),
                'is_super_admin' => $engineer['user_id'] == 1
            ];
        }
        return $results;
    }

    /**
     * 获取品质部及所有子部门数据
     *
     * @return array
     */
    private static function getSubDepts()
    {
        $topDept = DeptModel::query()->where('name', self::DEPT_NAME)->first();
        if (empty($topDept)) {
            return [];
        }
        $topDeptId = $topDept->id;
        $builder = DeptModel::query()
            ->where('pid', '=', $topDeptId)
            ->where('mark', '=', 1)
            ->select(['id', 'name']);
        $result = $builder->get()->keyBy('name')->toArray();
        $result[self::DEPT_NAME] = [
            'id' => $topDeptId,
            'name' => self::DEPT_NAME
        ];
        return $result;
    }
}